<template>
  <div class="tax-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>税务管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleExport">导出明细</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="税务类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择税务类型" clearable>
            <el-option
              v-for="item in taxTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴纳状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择缴纳状态" clearable>
            <el-option
              v-for="item in taxStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 税务统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>应缴税额</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.totalTax }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>已缴税额</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.paidTax }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>待缴税额</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.pendingTax }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>逾期税额</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.overdueTax }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 税务趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>税务趋势</span>
            <el-radio-group v-model="chartType" size="small">
              <el-radio-button label="monthly">月度</el-radio-button>
              <el-radio-button label="quarterly">季度</el-radio-button>
              <el-radio-button label="yearly">年度</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-container" ref="taxChartRef"></div>
      </el-card>

      <!-- 税务明细表格 -->
      <el-table
        v-loading="loading"
        :data="taxList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="taxNo" label="税务编号" width="180" />
        <el-table-column prop="type" label="税务类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTaxTypeTag(row.type)">
              {{ getTaxTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="税额" width="120">
          <template #default="{ row }">
            ¥ {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="缴纳期限" width="180" />
        <el-table-column prop="status" label="缴纳状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getTaxStatusTag(row.status)">
              {{ getTaxStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="缴纳时间" width="180" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 0"
              link
              type="success"
              @click="handlePay(row)"
            >
              缴纳
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 税务详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="税务详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="税务编号">{{ detail.taxNo }}</el-descriptions-item>
        <el-descriptions-item label="税务类型">
          <el-tag :type="getTaxTypeTag(detail.type)">
            {{ getTaxTypeLabel(detail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="税额">
          ¥ {{ detail.amount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="缴纳期限">{{ detail.dueDate }}</el-descriptions-item>
        <el-descriptions-item label="缴纳状态">
          <el-tag :type="getTaxStatusTag(detail.status)">
            {{ getTaxStatusLabel(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="缴纳时间">{{ detail.payTime }}</el-descriptions-item>
        <el-descriptions-item label="缴纳方式">{{ detail.payMethod }}</el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{ detail.transactionNo }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 缴税对话框 -->
    <el-dialog
      v-model="payDialogVisible"
      title="缴纳税款"
      width="500px"
    >
      <el-form
        ref="payFormRef"
        :model="payForm"
        :rules="payRules"
        label-width="100px"
      >
        <el-form-item label="税务编号">
          <span>{{ payForm.taxNo }}</span>
        </el-form-item>
        <el-form-item label="税务类型">
          <el-tag :type="getTaxTypeTag(payForm.type)">
            {{ getTaxTypeLabel(payForm.type) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="应缴税额">
          <span>¥ {{ payForm.amount?.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="缴纳方式" prop="payMethod">
          <el-select v-model="payForm.payMethod" placeholder="请选择缴纳方式">
            <el-option
              v-for="item in payMethods"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号" prop="transactionNo">
          <el-input v-model="payForm.transactionNo" placeholder="请输入交易流水号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="payForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPay">确认缴纳</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getTaxList, exportTaxList, getTaxStatistics, updateTaxInfo } from '@/api/finance'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  timeRange: []
})

// 税务类型选项
const taxTypes = [
  { label: '增值税', value: 'VAT' },
  { label: '企业所得税', value: 'INCOME_TAX' },
  { label: '个人所得税', value: 'PERSONAL_TAX' },
  { label: '其他税费', value: 'OTHER' }
]

// 税务状态选项
const taxStatus = [
  { label: '待缴纳', value: 0 },
  { label: '已缴纳', value: 1 },
  { label: '已逾期', value: 2 }
]

// 缴纳方式选项
const payMethods = [
  { label: '银行转账', value: 'BANK' },
  { label: '网上银行', value: 'ONLINE' },
  { label: '现金', value: 'CASH' }
]

// 统计数据
const statistics = ref({
  totalTax: 0,
  paidTax: 0,
  pendingTax: 0,
  overdueTax: 0
})

// 图表相关
const taxChartRef = ref(null)
let taxChart = null
const chartType = ref('monthly')

// 表格数据
const loading = ref(false)
const taxList = ref([])
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 缴税对话框
const payDialogVisible = ref(false)
const payFormRef = ref(null)
const payForm = ref({
  taxNo: '',
  type: '',
  amount: 0,
  payMethod: '',
  transactionNo: '',
  remark: ''
})

// 表单验证规则
const payRules = {
  payMethod: [
    { required: true, message: '请选择缴纳方式', trigger: 'change' }
  ],
  transactionNo: [
    { required: true, message: '请输入交易流水号', trigger: 'blur' }
  ]
}

// 获取税务类型标签
const getTaxTypeTag = (type) => {
  const map = {
    VAT: 'success',
    INCOME_TAX: 'warning',
    PERSONAL_TAX: 'danger',
    OTHER: 'info'
  }
  return map[type] || 'info'
}

// 获取税务类型标签文本
const getTaxTypeLabel = (type) => {
  const item = taxTypes.find(item => item.value === type)
  return item ? item.label : type
}

// 获取税务状态标签
const getTaxStatusTag = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || 'info'
}

// 获取税务状态标签文本
const getTaxStatusLabel = (status) => {
  const item = taxStatus.find(item => item.value === status)
  return item ? item.label : status
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getTaxList(queryParams.value)
    taxList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取税务列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getTaxStatistics(queryParams.value)
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 初始化税务趋势图
const initTaxChart = async () => {
  if (!taxChartRef.value) return
  
  taxChart = echarts.init(taxChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['应缴税额', '已缴税额']
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '应缴税额',
        type: 'bar',
        data: []
      },
      {
        name: '已缴税额',
        type: 'bar',
        data: []
      }
    ]
  }
  
  taxChart.setOption(option)
  
  // 获取税务趋势数据
  try {
    const res = await getTaxTrend({
      timeRange: queryParams.value.timeRange,
      type: chartType.value
    })
    const { data } = res
    taxChart.setOption({
      xAxis: {
        data: data.dates
      },
      series: [
        {
          data: data.totalAmounts
        },
        {
          data: data.paidAmounts
        }
      ]
    })
  } catch (error) {
    console.error('获取税务趋势数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStatistics()
  initTaxChart()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    status: undefined,
    timeRange: []
  }
  handleQuery()
}

// 导出按钮点击
const handleExport = async () => {
  try {
    const res = await exportTaxList(queryParams.value)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '税务明细.xlsx'
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleDetail = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 缴纳按钮点击
const handlePay = (row) => {
  payForm.value = {
    taxNo: row.taxNo,
    type: row.type,
    amount: row.amount,
    payMethod: '',
    transactionNo: '',
    remark: ''
  }
  payDialogVisible.value = true
}

// 提交缴纳
const submitPay = async () => {
  if (!payFormRef.value) return
  
  await payFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateTaxInfo(payForm.value.taxNo, {
          status: 1,
          payMethod: payForm.value.payMethod,
          transactionNo: payForm.value.transactionNo,
          remark: payForm.value.remark,
          payTime: new Date().toISOString()
        })
        ElMessage.success('缴纳成功')
        payDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('缴纳失败:', error)
        ElMessage.error('缴纳失败')
      }
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 监听图表类型变化
watch(chartType, () => {
  initTaxChart()
})

// 监听窗口大小变化
const handleResize = () => {
  taxChart?.resize()
}

onMounted(() => {
  handleQuery()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  taxChart?.dispose()
})
</script>

<style lang="scss" scoped>
.tax-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
    }
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .chart-container {
      height: 400px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style> 